package com.sds.sweng.swat.miplatform.ui.design.parts;

import java.util.List;

import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.FlowLayout;
import org.eclipse.draw2d.FreeformLayeredPane;
import org.eclipse.draw2d.IFigure;
import org.eclipse.gef.EditPolicy;

import com.sds.sweng.swat.miplatform.ui.design.layouts.FlowLayoutEx;
import com.sds.sweng.swat.miplatform.ui.design.models.MiplatformDesignModel;
import com.sds.sweng.swat.miplatform.ui.design.models.area.sub.SubArea;
import com.sds.sweng.swat.miplatform.ui.design.models.component.MForm;
import com.sds.sweng.swat.miplatform.ui.design.parts.area.AreaTemplatePart;
import com.sds.sweng.swat.miplatform.ui.design.parts.area.sub.TabContentsSubAreaPart;
import com.sds.sweng.swat.miplatform.ui.design.policies.DesignFlowLayoutEditPolicy;

public class MiplatformDesignPart extends MiplatformContainerPart {

	private static final int AREA_SPACING = 5;

	public boolean isSelectable() {
		return true;
	}

	protected IFigure createFigure() {
		if (MForm.TYPE_TAB_PAGE.equals(((MiplatformDesignModel) getModel()).getForm().getType())) {
			IFigure f = new Figure();
			f.setSize(((MiplatformDesignModel) getModel()).getForm().getAreaWidth(), SubArea.MODEL_HEIGHT);
			f.setOpaque(true);

			FlowLayoutEx layout = new FlowLayoutEx(false);
			layout.setStretchMinorAxis(true);
			layout.setMinorSpacing(AREA_SPACING);
			f.setLayoutManager(layout);

			return f;
		} else {
			Figure f = new FreeformLayeredPane();

			FlowLayout layout = new FlowLayout(false);
			layout.setStretchMinorAxis(true);
			layout.setMinorSpacing(AREA_SPACING);
			f.setLayoutManager(layout);

			return f;
		}
	}

	protected void createEditPolicies() {
		installEditPolicy(EditPolicy.LAYOUT_ROLE, new DesignFlowLayoutEditPolicy());
	}

	public void resizeFigure() {
		if (MForm.TYPE_TAB_PAGE.equals(((MiplatformDesignModel) getModel()).getForm().getType())) {
			int height = SubArea.MODEL_HEIGHT;

			List<AreaTemplatePart> areaTemplateParts = getChildren();

			for (int i=0;i<areaTemplateParts.size();i++) {
				height += areaTemplateParts.get(i).getFigure().getSize().height;

				if (i < areaTemplateParts.size()-1)
					height += AREA_SPACING;
			}

			getFigure().setSize(((MiplatformDesignModel) getModel()).getForm().getAreaWidth(), height);

			((TabContentsSubAreaPart) getParent()).resizeFigure(height);
		}
	}

}
